#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：idi_mes 
@File    ：input_vehicle_instation.py
@IDE     ：PyCharm 
@Date    ：9/25/24 9:52 AM
"""
from typing import Dict, Union, List

from mg_app_framework import MesCode, get_logger, get_organization

from common.basic_mongo import get_mongo_collection
from common.retrospect_operate.handle import publish_retrospect_nodes
from prod_ctrl_service.tool.tool import get_time, check_cell_sn_consistent, device_workorder, batch_make_retros_in


async def check_input_vehicle_instation(params: Dict[str, Union[str, List[Dict[str, str]]]]) \
        -> Dict[str, str]:
    """
    MES系统验证上位机上传的电芯码和MES记录的一致、且托盘码符合进站条件
    :param params:{
               "call_id":"JQ00386",  #接口调用方认证ID, string
               "trace_id":"8941d16b-0581-4e68-8940-a651afff4282",  #接口调用ID, string
               "upperpc_code": "UP011",    #上位机编码, string
               "user_code":"Y001",  #员工编码, string
               "equip_code":"ZP001",  # 设备编码, string
               "process_code":"2050",   # 工序编码, string, 必输
               "vehicle_no":"20001",   #载具编码, string, Y, MES和上位机统一编码
               "cell_list": [    # 电芯列表, 数组, Y
                  {
                     "cell_sn": "WW202408140001",   # 电芯码, string, Y
                     "slot_no": "11"       # 通道号, string
                  },
                  {
                     "cell_sn": "WW202408140002",
                     "slot_no": "12"
                  }
               ]
            }
    :return:
    """
    error_msg = ""
    device_code = params.get("equip_code")
    vehicle_no = params.get("vehicle_no")
    cell_list = params.get("cell_list")
    cell_sn_list = [rec["cell_sn"] for rec in cell_list]
    # 对比托盘码在数据库中绑定的电芯码是否与入参中的电芯码一致
    if_consistent, check_result, cell_sn_list_in_db = await check_cell_sn_consistent(vehicle_no, cell_sn_list)
    if not if_consistent:
        return check_result
    # 进站时创建进站的追溯数据，这部分功能后续修改为调用提供的进站数据追溯数据创建接口
    work_order = await device_workorder(device_code)
    insert_data_list = batch_make_retros_in(wip_list=cell_sn_list_in_db, work_order=work_order)
    try:
        for rec_item in insert_data_list:
            await publish_retrospect_nodes(device_code=device_code, retrospect_items=[rec_item])
        get_logger().info(f"码值{cell_sn_list_in_db}进站追溯数据已建立")
    except ValueError as e:
        error_msg += str(e)

    if error_msg:
        result = {
            "code": MesCode.fail,  # 接口应答状态代码, success：成功; fail：失败, string
            "data": {},  # 接口返回结果描述, json数组, 本接口不需要返回数据，返回null
            "info": error_msg,  # 接口返回信息描述, 如果为fail, 则为fail的异常描述信息, string
        }
        return result

    # 在制品进站的入参每一次调用成功后存储
    input_data = {
        "call_id": params.get("call_id"),  # 接口调用方认证ID, string
        "trace_id": params.get("trace_id"),  # 接口调用ID, string
        "upperpc_code": params.get("upperpc_code"),  # 上位机编码, string
        "user_code": params.get("user_code"),  # 员工编码, string
        "equip_code": params.get("equip_code"),  # 设备编码, string
        "process_code": params.get("process_code"),  # 工序编码, string, 必输
        "vehicle_no": params.get("vehicle_no"),  # 载具编码, string, Y, MES和上位机统一编码
        "cell_list": params.get("cell_list"),  # 电芯列表, 数组, Y
        "time": get_time()
    }
    await insert_data(input_data)

    result = {
        "code": MesCode.success,  # 接口应答状态代码, success：成功; fail：失败, string
        "data": {},  # 接口返回结果描述, json数组, 本接口不需要返回数据，返回null
        "info": f"OK",  # 接口返回信息描述, 如果为fail, 则为fail的异常描述信息, string
    }
    return result


async def insert_data(data):
    """
    登记当前投料蓝胶码/电芯码
    :param data:
    :return:
    """
    collection = get_mongo_collection(
        database_name=f"{get_organization()}_mes",
        collection_name=f"input_vehicle_instation_record",
    )
    await collection.insert_one(data)
